package com.ndood.spider.taobaomix.pipeline;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.ndood.core.util.ImageDownloadUtil;
import com.ndood.core.util.PropertiesUtil;
import com.ndood.spider.taobaomix.bean.TaobaoMixGoods;
import com.ndood.spider.taobaomix.dao.TaobaoMixGoodsDao;

import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

/**
 * 处理结果
 * 
 * @author qilongfei
 *
 */
@Component
public class TaobaoMixPipeline implements Pipeline {
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private TaobaoMixGoodsDao spider2Dao;

	@Override
	public void process(ResultItems resultItems, Task task) {
		for (Map.Entry<String, Object> entry : resultItems.getAll().entrySet()) {
			if (!entry.getKey().contains("goods")) {
				continue;
			}
			TaobaoMixGoods goods = (TaobaoMixGoods) entry.getValue();
			if (goods == null) {
				continue;
			}
			dealWithOneTaobao2Goods(goods);
		}
	}

	public void dealWithOneTaobao2Goods(TaobaoMixGoods goods) {
		String dir = PropertiesUtil.readProperty("logging.path");
		try {
			// Step1: 保存图片
			String goodsDir = dir + File.separator + goods.getId();
			savePics(goods.getImgUrls(), goodsDir + File.separator + "imgs");
			savePics(goods.getColorUrls(), goodsDir + File.separator + "colors");
			savePics(goods.getDescUrls(), goodsDir + File.separator + "descs");

			// Step2: 保存商品信息到DB
			if (spider2Dao == null) {
				saveExcel(dir, goods);
			} else {
				save2DB(goods);
			}
			

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("保存商品异常" + goods.getId());
		}
		
		System.out.println("done");
	}

	/**
	 * 保存商品信息到excel
	 */
	private void saveExcel(String dir, TaobaoMixGoods goods) {
		File file = new File(dir);
		if (!file.exists()) {
			file.mkdirs();
		}
		// logger.info(new Gson().toJson(goods));
		File goodsFile = new File(dir + File.separator + goods.getId()+"-"+goods.getName());
		if(goodsFile.exists()){
			return;
		}
		FileWriter fw = null;
		try {
			fw = new FileWriter(goodsFile, true);
			fw.write(new Gson().toJson(goods));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fw.close();
			} catch (IOException e) {
			}
		}

	}

	/**
	 * 保存商品信息到excel
	 */
	private void save2DB(TaobaoMixGoods goods) {
		// spider2Dao.updateGoodsWithoutCatUrl(goods);
		if(spider2Dao.get(goods.getId())==null){
			spider2Dao.insert(goods);
		}else{
			spider2Dao.update(goods);
		}
	}

	/**
	 * 保存图片 url1,url2, dir
	 */
	private void savePics(Map<String, String> map, String dir) {
		File file = new File(dir);
		if (!file.isDirectory()) {
			file.mkdirs();
		}
		for (Iterator<String> i = map.keySet().iterator(); i.hasNext();) {
			String name = i.next();
			String url = map.get(name);
			name = name.replace("\\\\", "_").replaceAll("/", "_");
			if (!url.contains("http")) {
				url = "http:" + url;
				ImageDownloadUtil.download(dir, url, name, ".png");
			}
		}
	}

	public void redownload(TaobaoMixGoods goods) {
		try {
			String dir = PropertiesUtil.readProperty("logging.path");
			String goodsDir = dir + File.separator + goods.getId();
			savePics(goods.getImgUrls(), goodsDir + File.separator + "imgs");
			savePics(goods.getDescUrls(), goodsDir + File.separator + "descs");
		} catch (Exception e) {
		}
	}
}
